<?php

namespace App\Admin\Controllers;

use App\Models\Administrator;
use App\Models\Department;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Tree;
use Dcat\Admin\Widgets\Box;
use Dcat\Admin\Widgets\Form as WidgetForm;

class DepartmentController extends AdminController
{


    public function index(Content $content)
    {
        return $content
            ->title($this->title())
            ->description(trans('admin.list'))
            ->body(function (Row $row) {
                $row->column(7, $this->treeView()->render());

                $row->column(5, function (Column $column) {
                    $form = new WidgetForm();
                    $form->action(admin_url('departments'));

                    $form->select('parent_id', '父级部门')
                        ->options(Department::selectOptions())
                        ->default(0)
                        ->required();
                    $form->text('title', '部门名称')->required();

                    $form->width(9, 2);

                    $column->append(Box::make(trans('admin.new'), $form));
                });
            });
    }

    /**
     * @return \Dcat\Admin\Tree
     */
    protected function treeView()
    {
        return new Tree(new Department(), function (Tree $tree) {
            $tree->disableCreateButton();
            $tree->disableQuickCreateButton();
            $tree->disableEditButton();
            $tree->maxDepth(3);

            $tree->actions(function (Tree\Actions $actions) {
                if ($actions->getRow()->extension) {
                    $actions->disableDelete();
                }
            });

            $tree->branch(function ($branch) {
                $payload = "<strong>{$branch['title']}</strong>";

                return $payload;
            });
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Department(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('parent_id');
            $grid->column('order');
            $grid->column('title');
            $grid->column('depth');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Department(), function (Show $show) {
            $show->field('id');
            $show->field('parent_id');
            $show->field('order');
            $show->field('title');
            $show->field('depth');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(Department::with(['users' => function ($q) {
            $q->withPivot('is_manager')->select(['id']);
        }]), function (Form $form) {

            $form->display('id');
            $form->select('parent_id', '父级部门')->options(Department::selectOptions());
            $form->text('title');
            $options = Administrator::query()->select(['id', 'name'])
                ->pluck('name', 'id');
            $form->table('users', '部门成员', function (Form\NestedForm $form) use ($options) {

                $form->select('user_id', '用户')
                    ->options($options)
                    ->required();
                $form->switch('is_manager', '是否为部门管理员');
            })->customFormat(function ($val) {
                return collect($val)->map(function ($item) {
                    return [
                        'user_id' => data_get($item, 'pivot.user_id'),
                        'is_manager' => data_get($item, 'pivot.is_manager'),
                    ];
                });
            })->saving(function ($val) {
                $result = [];
                foreach ($val as $user) {
                    $result[$user['user_id']] = [
                        'is_manager' => data_get($user, 'is_manager', 0)
                    ];
                }
                return $result;
            });
        })->saving(function (Form $form) {
            if (!request()->exists(['_file_', 'upload_column', 'size'])) {
                if ($users = $form->input('users')) {
                    $users = collect($users)
                        ->filter(function ($item) {
                            return !$item['_remove_'] && $item['user_id'];
                        })
                        ->unique('user_id')
                        ->toArray();

//                    dd($result);
                    $form->input('users', $users);

                }
            }
        });
    }
}
